package s02;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @ClassName FileUploadServer
 * @Description TODO
 * @Author Li
 * @Date 2022/9/9 0:57
 * @ModifyDate 2022/9/9 0:57
 * @Version 1.0
 */
public class FileUploadServer {
    public static void main(String[] args) throws IOException {
        System.out.println("服务器启动...");
        // 1.创建服务端ServerSocket
        ServerSocket server = new ServerSocket(6666);
        while (true) {
            // 2.建立连接
            Socket socket = server.accept();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        // 3.创建流对象
                        // 3.1获取输入流，读取文件数据
                        BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
                        // 3.2创建输出流，保存到本地
                        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D:\\" + System.currentTimeMillis() + ".png"));
                        // 4.读写数据
                        int len = 0;
                        byte[] bytes = new byte[10240];
                        while ((len = bis.read(bytes)) != -1) {
                            bos.write(bytes, 0, len);
                        }
                        System.out.println("文件上传成功！！！");

                        /* 信息回写 */
                        System.out.println("信息回写...");
                        OutputStream os = socket.getOutputStream();
                        os.write("回写上传成功！".getBytes());
                        os.close();

                        // 5.关闭资源
                        bos.close();
                        bis.close();
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }
}
